package com.yoga.admin.api.interceptor;


import com.yoga.admin.api.annotation.UserTokenManage;
import com.yoga.common.appexception.AppErrorCodeEnum;
import com.yoga.common.appexception.AppException;
import com.yoga.common.bo.YogaAdminBO;
import com.yoga.common.util.Config;
import com.yoga.common.util.MD5Util;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by chenjin on 2019/6/26.
 */
public class SignInterceptor implements HandlerInterceptor {

    private Logger log = LoggerFactory.getLogger(SignInterceptor.class);


    private ValueOperations valueOperations;

    public  SignInterceptor(ValueOperations valueOperations){
        this.valueOperations=valueOperations;
    }


    /**
     * 项目签名私钥
     */
    private final static String secretKey = "yogaAdmin@1$";

    /**
     *  需要开通VIP的接口URL验证
     */
    private static Map<String, String> vipUrlMap = new HashMap<>();

    /**
     * 不需要登录的URL
     */
    private static Map<String, String> loginMap = new HashMap<>();

    static {
        loginMap.put("/admin/register", "注册接口");
        loginMap.put("/admin/login", "登录接口");
        loginMap.put("/admin/upload-image", "图片上传接口");
        loginMap.put("/admin/send/code", "发送验证码接口");
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws Exception {

        //用于自测的时候放开接口签名验证
        if (StringUtils.isNotEmpty(request.getHeader("signStatus"))) {
            Integer signStatus = Integer.valueOf(request.getHeader("signStatus"));
            if (signStatus == 0) {
                return true;
            }
        }
        //接口签名验证
        String sign = request.getHeader("sign");
        String timestamp = request.getHeader("timestamp");

        if (StringUtils.isEmpty(sign) || StringUtils.isEmpty(timestamp)) {
            throw new AppException(AppErrorCodeEnum.SIGN_ISNULL);
        }
        StringBuffer buffer = new StringBuffer();
        buffer.append(secretKey).append(timestamp);
        String sysSign = MD5Util.encryption(buffer.toString());

        if (!sysSign.equals(sign)) {
            log.error("签名错误 ： sign:{},sysSign:{},timestamp:{}",sign,sysSign,timestamp);
            throw new AppException(AppErrorCodeEnum.SIGN_ERROR);
        }

        //不需要登录的接口过滤
        String url = request.getRequestURI();
        if (StringUtils.isNotBlank(loginMap.get(url))){
          return true;
        };

        String yogaAdminId= (String) request.getHeader(Config.YOGA_ADMIN_ID);
        if (StringUtils.isBlank(yogaAdminId)){
            throw new AppException(AppErrorCodeEnum.UN_LOGN);
        }

        YogaAdminBO yogaAdminBO= UserTokenManage.getInstance(valueOperations).getLoginUser(Long.parseLong(yogaAdminId));
        if (yogaAdminBO==null){
            throw new AppException(AppErrorCodeEnum.UN_LOGN);
        }
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
    }


}
